package com.zzl.car.service;

import com.zzl.car.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value="/auditLicense/{telephone}")
@Component
public class zdpWebSocket {

    private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
    private static final ThreadLocal<String> telephone = new ThreadLocal<>();
/*
* if(authorization==null){
            System.out.println("===================sec-webSocket-protocol===============");
            authorization = request.getHeader("Sec-WebSocket-Protocol");
            System.out.println(authorization);
        }
* */
    @OnOpen
    public void onOpen(Session session, @PathParam("telephone") String telephone){
        //审核的连接连接
        System.out.println("连接上了");
        System.out.println(session);
        System.out.println(telephone);
        this.telephone.set(telephone);
        sessions.put(telephone,session);
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("连接关闭");
        sessions.remove(telephone.get());
    }

    @OnMessage
    public void onMsg(String message){
        System.out.println("接收到的消息"+message);
    }

    /*
    * 发送消息
    * */
    public void sendMessageByUser(String telephone,User user){
        try {
            sessions.get(telephone).getBasicRemote().sendObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }

    public void sendMessageByString(String telephone,String message){
        try {
            sessions.get(telephone).getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
